from datetime import datetime
import requests
import json
from typing import List, Optional
import logging

class DingDingRobot:
    """钉钉机器人消息发送工具"""
    def __init__(self, access_token: Optional[str] = None, keyword: str = None):
        self._keyword = keyword
        self.access_token = access_token
        self.url = f'https://oapi.dingtalk.com/robot/send?access_token={self.access_token}'
        self.headers = {"Content-Type": "application/json;charset=UTF-8"}
        self.logger = logging.getLogger(__name__)
        
        # 默认要@的手机号列表
        self.default_at_mobiles = []

    def _send_request(self, payload: dict) -> bool:
        """发送请求到钉钉"""
        try:
            response = requests.post(
                url=self.url,
                headers=self.headers,
                data=json.dumps(payload)
            )
            response.raise_for_status()
            return True
        except Exception as e:
            self.logger.error(f"钉钉消息发送失败: {str(e)}")
            return False

    def _format_message(self, msg: str) -> str:
        """格式化消息内容"""
        return f'yukalix, 消息内容: {msg}\n发送时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}'

    def send_message(self, msg: str, at_mobiles: Optional[List[str]] = None) -> bool:
        """发送普通消息"""
        formatted_msg = self._format_message(msg)
        payload = {
            'msgtype': 'text',
            'text': {'content': formatted_msg},
            'at': {'atMobiles': at_mobiles or self.default_at_mobiles}
        }
        return self._send_request(payload)

    def send_error_message(self, file: str, msg: str, at_mobiles: Optional[List[str]] = None) -> bool:
        """发送错误消息"""
        error_msg = f'错误提醒!\n文件位置: {file}\n{msg}'
        return self.send_message(error_msg, at_mobiles)


    def send_markdown_message(self, title: str, content: str, at_mobiles: Optional[List[str]] = None) -> bool:
        """发送markdown格式消息"""
        payload = {
            'msgtype': 'markdown',
            'markdown': {
                'title': f'{self._keyword},{title}',
                'text': f'{content}\n\n发送时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}'
            },
            'at': {'atMobiles': at_mobiles or self.default_at_mobiles}
        }
        return self._send_request(payload)

